<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2012 Chi Hoang <info@chihoang.de>
*  All rights reserved
*
***************************************************************/
require_once ( t3lib_extMgm::extPath ( 'ch_raetseltreff' ) . 'classes/class.tx_ch1_framework.php');

define("ETA2NEVT", 3*86400+7200);
define("ETA5NEVT", 6*86400+7200);
define("ETA1VEVT", 1*86400+7200);
define("ETA6NEVT", 6*86400+7200);
define("ETA30VEVT", 30*86400+7200);
define("WEEK", 7*86400+7200);

/**
 * Plugin 'ch_raetseltreff' for the 'ch_raetseltreff' extension.
 *
 * @author	Chi Hoang <info@chihoang.de>
 * @package	TYPO3
 * @subpackage	tx_chraetseltreff
 */
class tx_chraetseltreff_pi1 extends tx_ch1_framework
{
	var $prefixId      = 'tx_chraetseltreff_pi1';		// Same as class name
	var $scriptRelPath = 'pi1/class.tx_chraetseltreff_pi1.php';	// Path to this script relative to the extension dir.
	var $extKey        = 'ch_raetseltreff';	// The extension key.
	
	// Meine Variablen
	var $lConf;
	
	public $taktung = array ( "0" => "+2 day",
							  "1" => "+5 day",
							  "2" => "+1 Month"
							);
	
	public $kuerzel = array ( "0" => "Mon",
							  "1" => "Tue",
							  "2" => "Wed",
							  "3" => "Thu",
							  "4" => "Fri",
							  "5" => "Sat",
							  "6" => "Mon"
							 );

	function createMonth($arr, $number)
	{
		$m [ "###TITLE###" ] = $arr [ "PT" ] . " " . $number;
		$m [ "###TITLEBILD###" ] = "<img width=\"172\" height=\"235\" src=\"uploads/tx_chraetseltreff/" .
											$arr [ "filename" ] . sprintf("%02d", $number) .".jpg\" />";
		
		$m [ "###URL###" ] =  $this->pi_getPageLink ( $GLOBALS [ 'TSFE' ]->id, '',
											array ( "uid" => $arr [ "UID" ],
													"mode" => "s",
													"kw" => $number,
													"heft" => $arr [ "filename" ] . $number. ".jpg"
												   )
											);
		return $this->cObj->substituteMarkerArray ( $this->template [ 'ZEITSCHRIFT' ], $m  );
	}
								
	function createWeek($arr, $number)
	{
		$m [ "###TITLE###" ] = $arr [ "PT" ] . " " . $number;
		$m [ "###TITLEBILD###" ] = "<img width=\"172\" height=\"235\" src=\"uploads/tx_chraetseltreff/" .  $arr [ "filename" ] . $number.".jpg\" />"; 
	
		$m [ "###URL###" ] =   $this->pi_getPageLink ( $GLOBALS [ 'TSFE' ]->id, '',
											array ( "uid" => $arr [ "UID" ],
													"mode" => "s",
													"kw" => $number,
													"heft" => $arr [ "filename" ] . $number. ".jpg"
												   )
											);
		return $this->cObj->substituteMarkerArray ( $this->template [ 'ZEITSCHRIFT' ], $m  );	
	}
	
	function convertMonth($arr, $number)
	{	
		if (!file_exists($this->confArray["uploadPath"]."/".$arr["filename"].sprintf("%02d", $number).".jpg") &&
			!file_exists($this->confArray["datenanlieferung"]."/".strtoupper($arr["filename"]).sprintf("%02d", $number).$arr["suffix"]))
		{
			$pdf = strtoupper($arr["filename"]).sprintf("%02d", $number).$arr["suffix"];
			$mail = t3lib_div::makeInstance('t3lib_mail_message');
			$mail->setFrom(array($arr["emailreplyemail"] => $arr["emailreplyname"]));
			$mail->setTo(array($arr["emailtoemail"] => $arr["emailtoname"]));
			$mail->setSubject(str_replace("###MAGAZIN###",$pdf,$arr["emailsubject"]));
			$mail->setBody(str_replace("###MAGAZIN###",$pdf,$arr["emailbody"]));
			$mail->addPart(str_replace("###MAGAZIN###",$pdf,$arr["emailbody"]));
			$mail->send();
			
			return false;	
		} else
		{
			//exec('convert '.$this->confArray["datenanlieferung"]."/".strtoupper($arr["filename"]).sprintf("%02d", $number).$arr["suffix"].
			// ' -colorspace RGB -scale 172x235 '.$this->confArray["uploadPath"]."/".$arr["filename"].sprintf("%02d", $number).".jpg");	
		}
		return true;
	}
	
	function convertWeek($arr, $number)
	{
		if (!file_exists($this->confArray["uploadPath"]."/".$arr["filename"].$number.".jpg") &&
			!file_exists($this->confArray["datenanlieferung"]."/".strtoupper($arr["filename"]).$number.$arr["suffix"]))
		{
			$pdf = strtoupper($arr["filename"]).$number.$arr["suffix"];
			$mail = t3lib_div::makeInstance('t3lib_mail_message');
			$mail->setFrom(array($arr["emailreplyemail"] => $arr["emailreplyname"]));
			$mail->setTo(array($arr["emailtoemail"] => $arr["emailtoname"]));
			$mail->setSubject(str_replace("###MAGAZIN###",$pdf,$arr["emailsubject"]));
			$mail->setBody(str_replace("###MAGAZIN###",$pdf,$arr["emailbody"]));
			$mail->addPart(str_replace("###MAGAZIN###",$pdf,$arr["emailbody"]));
			$mail->send();
			
			return false;	
		} else
		{
			//exec('convert '.$this->confArray["datenanlieferung"]."/".strtoupper($arr["filename"]).$number.$arr["suffix"].
			// ' -colorspace RGB -scale 172x235 '.$this->confArray["uploadPath"]."/".$arr["filename"].$number.".jpg");
		}
		return true;		
	}
	
		// return timestamp of last Monday...Friday
	function last_dayofweek($uid, $day, $taktung, $week=0)
	{
		$kuerzel = $this->kuerzel[$day];
		$takt = $this->taktung[$taktung];
		$einsendeschluss = strtotime("last {$kuerzel} {$takt} {$week}");
		
		$res = $GLOBALS [ 'TYPO3_DB' ]->exec_SELECTquery (
			'P.title PT, P.uid UID, S.title ST, S.specialdate SD',
			'tx_chraetseltreff_print P LEFT JOIN tx_chraetseltreff_special S ON P.special=S.uid',
			'P.pid='. $this->lConf [ "sysfolder" ].' AND P.deleted=0 AND P.hidden=0',
			'',
			'P.sorting ASC'
		);
		
		$weekNumber1 = date("W", $einsendeschluss);
	
		while ( $row = $GLOBALS [ 'TYPO3_DB' ]->sql_fetch_assoc ( $res ) )
		{
			$weekNumber2 = date("W", $row["specialdate"]);
			
			if ($weekNumber1 == $weekNumber2)
			{
				$day = date("W", $row["SD"]);
				$einsendeschluss = strtotime("last {$day} {$takt} {$week}");
			}
		}
		
		if ( $einsendeschluss >= time() )
		{
			$bool = true;	
		} else
		{
			$bool = false;
		}
		return $bool;
	}

	function getFirstDayMonth ($uid, $day, $y, $m, $taktung)
	{
		$takt = $this->taktung[$taktung];
		$kuerzel = $this->kuerzel[$day];
		
		if ((int)$m > 12)
		{
			$m = (int)1;
			$y = (int)$y+1;	
		}
		
		$einsendeschluss = strtotime($kuerzel." $y-$n $takt") ;
		
		$res = $GLOBALS [ 'TYPO3_DB' ]->exec_SELECTquery (
			'P.title PT, P.uid UID, S.title ST, S.specialdate SD',
			'tx_chraetseltreff_print P LEFT JOIN tx_chraetseltreff_special S ON P.special=S.uid',
			'P.pid='. $this->lConf [ "sysfolder" ].' AND P.deleted=0 AND P.hidden=0',
			'',
			'P.sorting ASC'
		);
		
		$monthNumber1 = date("n", $einsendeschluss);
	
		while ( $row = $GLOBALS [ 'TYPO3_DB' ]->sql_fetch_assoc ( $res ) )
		{
			$monthNumber2 = date("n", $row["SD"]);
			
			if ($monthNumber1 == $monthNumber2)
			{
				$day = date("W", $row["specialdate"]);
				$einsendeschluss = strtotime("last {$day} {$takt} {$week}");
			}
		}
		
		if ( $einsendeschluss >= time() )
		{
			$bool = true;	
		} else
		{
			$bool = false;
		}
		return $bool;
	}
	
	
	/**
	 * The main method of the PlugIn
	 *
	 * @param	string		$content: The PlugIn content
	 * @param	array		$conf: The PlugIn configuration
	 * @return	The content that is displayed on the website
	 */
	function main($content, $conf)
	{	
		
		$this->conf = $conf;
		$this->pi_setPiVarDefaults();
		$this->pi_loadLL();
		$this->pi_USER_INT_obj = 1;	// Configuring so caching is not expected. This value means that no cHash params are ever set. We do this, because it's a USER_INT object!
	
			// Conf
		$this->confArray = unserialize ( $GLOBALS [ 'TYPO3_CONF_VARS' ][ 'EXT' ][ 'extConf' ] [ $this->extKey ] );	
		$this->pi_initPIflexForm ( );			// Init and get the flexform data of the plugin

			// Assign the flexform data to a local variable for easier access
		$piFlexForm = $this->cObj->data [ 'pi_flexform' ];
		$index = $this->lang [ $GLOBALS [ 'TSFE' ]->sys_language_uid ] == null ? 0 : $this->lang [ $GLOBALS [ 'TSFE' ]->sys_language_uid ];
		$sDef = current ( $piFlexForm [ 'data' ] );
		$lDef = array_keys ( $sDef );
        
		foreach ( $piFlexForm [ 'data' ] as $sheet => $data )
		{
			foreach ( $data [ $lDef [ $index ] ] as $key => $val )
			{
				$this->lConf [ $key ] = $this->pi_getFFvalue ( $piFlexForm, $key, $sheet,
									      $lDef[$index] );
			}
		}

		$js .= $this->getCSSInclude ( t3lib_extMgm::siteRelPath ( 'ch_raetseltreff' ) . 'res/',
					     'system.css' );
		//$js .= $this->getJavascriptInclude ( t3lib_extMgm::siteRelPath ( 'ch_raetseltreff' ) .
		//				    'res/', 'modernizr.custom.94949.js' );
		$js .= $this->getJavascriptInclude ( t3lib_extMgm::siteRelPath ( 'ch_raetseltreff' ) .
						    'res/', 'jquery-1.7.2.min.js' );
		$js .= $this->getJavascriptInclude ( t3lib_extMgm::siteRelPath ( 'ch_raetseltreff' ) .
						    'res/', 'jquery.masonry.min.js' );
		$js .= $this->getJavascriptInclude ( t3lib_extMgm::siteRelPath ( 'ch_raetseltreff' ) .
						    'res/', 'jquery.validate.min.js' );
		$js .= $this->getJavascriptInclude ( t3lib_extMgm::siteRelPath ( 'ch_raetseltreff' ) .
						    'res/', 'messages_de.js' );
		$js .= $this->getJavascriptInclude ( t3lib_extMgm::siteRelPath ( 'ch_raetseltreff' ) .
						    'res/', 'treff.js' );
		
		$GLOBALS [ 'TSFE' ]->additionalHeaderData [ $this->prefixId ] = $js;

			// Get the template
 		$this->templateCode = $this->cObj->fileResource ( $this->confArray [ 'uploadPath' ] . '/' .
								$this->lConf [ 'template_file' ] );

		switch ( $_GET [ "mode"] )
		{
			case "i":
			{
				$res = $GLOBALS['TYPO3_DB']->exec_DELETEquery("tx_chraetseltreff_user", 'werbung=0 AND tstamp < '.(time()-ETA30VEVT));
				$res = $GLOBALS['TYPO3_DB']->exec_DELETEquery("tx_chraetseltreff_spiel", 'tstamp < '.(time()-ETA30VEVT));
				$q = "DELETE s From tx_chraetseltreff_spiel s WHERE user_id NOT IN (SELECT uid from tx_chraetseltreff_user WHERE uid is not null)";
				$res = $GLOBALS['TYPO3_DB']->sql_query($q);
					
				$this->template [ 'LANDINGPAGE' ] = $this->cObj->getSubpart ( $this->templateCode, '###LANDINGPAGE###' );
				unset ( $m );
				$m ["###BACK###"] = $this->pi_getPageLink ( $GLOBALS [ 'TSFE' ]->id, '' );
	
				$res = $GLOBALS [ 'TYPO3_DB' ]->exec_SELECTquery (
					'V.title VT, V.uid UID, evt_woche, filename, email,replyname,replyemail,alt_template',
					'tx_chraetseltreff_print V',
					'pid='.	mysql_real_escape_string ( $this->lConf [ "sysfolder" ] ) .
					' AND uid='. mysql_real_escape_string ( $_GET [ "uid" ] ).
					' AND V.deleted=0 AND V.hidden=0',
					'',
					'sorting ASC'
				);
				$rec = $GLOBALS [ 'TYPO3_DB' ]->sql_fetch_assoc ( $res );
				
				$heftredaktion = $m ["###REDAKTION###"] = $rec [ "VT"];
				$replyname = $rec ["replyname"];
		        $replyemail = $rec ["replyemail"];
				$emailadresse = $rec ["email"];
				
				$c = $this->cObj->substituteMarkerArray ( $this->template [ 'LANDINGPAGE' ], $m  );
				
				$r = array (
					'pid' => mysql_real_escape_string($this->lConf [ "sysfolder" ]),
					'tstamp' => time(),
					'crdate' => time()
				);	
				$r [ "agb" ] = $_POST [ "agb" ] == "on" ? "1" : "0";
				$r [ "werbung" ] = $_POST [ "werbung" ] == "on" ? "1" : "0";
				$r [ "anrede"] = mysql_real_escape_string ($_POST [ "anrede"]);
				$r [ "email" ] = mysql_real_escape_string ($_POST [ "email" ]);
				$r [ "hausnummer" ] = mysql_real_escape_string ($_POST [ "hausnummer" ]);
				$r [ "hinweise" ] = mysql_real_escape_string ($_POST [ "hinweise" ]);
				$r [ "name" ] = mysql_real_escape_string ($_POST [ "name" ]);
				$r [ "ort" ] = mysql_real_escape_string ($_POST [ "ort" ]);
				$r [ "plz" ] = mysql_real_escape_string ($_POST [ "postleitzahl" ]);
				$r [ "strasse" ] = mysql_real_escape_string ($_POST [ "strasse" ]);
				$r [ "telefon" ] = mysql_real_escape_string ($_POST [ "telefon" ]);
				$r [ "vorname" ] = mysql_real_escape_string ($_POST [ "vorname" ]);
				$res = $GLOBALS['TYPO3_DB']->exec_INSERTquery( "tx_chraetseltreff_user" , $r);
			
				$r = array (
					'pid' => mysql_real_escape_string($this->lConf [ "sysfolder" ]),
					'tstamp' => time(),
					'crdate' => time(),
					"title" => mysql_real_escape_string(strtoupper($_POST["loesungswort"])),
					"print_id" => mysql_real_escape_string($_POST["uid"]),
					"user_id" => $GLOBALS['TYPO3_DB']->sql_insert_id(),
					"kw" => mysql_real_escape_string($_GET["kw"]),
				);
				$res = $GLOBALS['TYPO3_DB']->exec_INSERTquery( "tx_chraetseltreff_spiel" , $r);
			
				if ( $rec ["alt_template"] )
				{
					$r = array (
						'pid' => mysql_real_escape_string($this->lConf["sysfolder"]),
						'tstamp' => time(),
						'crdate' => time(),
						"title" => mysql_real_escape_string($_POST["sudoku"]),
						"print_id" => mysql_real_escape_string($_POST["uid"]),
						"user_id" => $GLOBALS['TYPO3_DB']->sql_insert_id(),
						"kw" => mysql_real_escape_string($_GET["kw"]),
					);
					$res = $GLOBALS['TYPO3_DB']->exec_INSERTquery( "tx_chraetseltreff_spiel", $r);
				}
			
				unset($m);
				$this->template [ 'HTMLMAIL' ] = $this->cObj->getSubpart ( $this->templateCode, '###HTMLMAIL###' );
				$this->template [ 'PLAINTEXTMAIL' ] = $this->cObj->getSubpart ( $this->templateCode, '###PLAINTEXTMAIL###' );
				$m ["###REDAKTION###"] = $heftredaktion;
				$a = $this->cObj->substituteMarkerArray ( $this->template [ 'HTMLMAIL' ], $m  );
				$d = $this->cObj->substituteMarkerArray ( $this->template [ 'PLAINTEXTMAIL' ], $m  );
				
				$mail = t3lib_div::makeInstance('t3lib_mail_message');
				$mail->setFrom(array($replyemail => $replyname));
				$mail->setTo(array($_POST["email"] => $_POST [ "name" ]));
				$mail->setSubject($heftredaktion . "Gewinnspiel");
				$mail->setBody($a);
				$mail->addPart($d);
				$mail->send();	
			}
			break;
		
			case "s":
			{
				$res = $GLOBALS [ 'TYPO3_DB' ]->exec_SELECTquery (
					'V.title VT, V.uid UID, evt_tag, evt_woche, filename, email, alt_template',
					'tx_chraetseltreff_print V',
					'pid='.	mysql_real_escape_string ( $this->lConf [ "sysfolder" ] ) .
					' AND uid='. mysql_real_escape_string ( $_GET [ "uid" ] ).
					' AND V.deleted=0 AND V.hidden=0',
					'',
					'sorting ASC'
				);
				$row = $GLOBALS [ 'TYPO3_DB' ]->sql_fetch_assoc ( $res );
				
				//die(print_r($row));
				
				if ( empty($row ["alt_template"]) )
				{			
					$this->template [ 'GEWINNSPIEL' ] = $this->cObj->getSubpart ( $this->templateCode, '###GEWINNSPIEL###' );
				} else
				{
					$this->template [ 'GEWINNSPIELSW' ] = $this->cObj->getSubpart ( $this->templateCode, '###GEWINNSPIELSW###' );
				}
				
				unset ( $m );
			
				if ( $row [ "evt_woche"] === "0")
				{
					$m [ "###TITLE###" ]  = $row [ "VT" ] . " " . $_GET["kw"]; 
					$m [ "###TITLEBILD###" ] = "<img width=\"172\" height=\"235\" src=\"uploads/tx_chraetseltreff/".$_GET["heft"]."\" />"; 
				} else
				{
					$m [ "###TITLE###" ]  = $row [ "VT" ] . " " . $_GET["kw"];
					$m [ "###TITLEBILD###" ] = "<img width=\"172\" height=\"235\" src=\"uploads/tx_chraetseltreff/".$_GET["heft"]."\" />";
				}
				
				$m ["###ONCLICK###"] = $m ["###FORM###"] = $this->pi_getPageLink ( $GLOBALS [ 'TSFE' ]->id, '',
															array ( "uid" => $_GET ["uid"],
																	"mode" => "i",
																	"kw" => $_GET["kw"],
																	"heft" => $_GET["heft"]
															)
														 );
				$c = $this->cObj->substituteMarkerArray ( $this->template [ 'GEWINNSPIEL' ], $m  );
			}
			break;
		
			default:
			{
				$this->template [ 'GALERIE' ] = $this->cObj->getSubpart ( $this->templateCode, '###GALERIE###' );
				$this->template [ 'ZEITSCHRIFT' ] = $this->cObj->getSubpart ( $this->templateCode, '###ZEITSCHRIFT###' );
				$this->template [ 'POST' ] = $this->cObj->getSubpart ( $this->templateCode, '###POST###' );
			
				$res = $GLOBALS [ 'TYPO3_DB' ]->exec_SELECTquery (
					'P.title PT, P.uid UID, evt_tag, evt_woche, filename, taktung, suffix, replyname, replyemail, P.email, R.*',
					'tx_chraetseltreff_print P LEFT JOIN tx_chraetseltreff_redaktion R ON P.email=R.uid',
					'P.pid='. $this->lConf [ "sysfolder" ].' AND P.deleted=0 AND P.hidden=0',
					'',
					'sorting ASC'
				);				
				 
				while ( $row = $GLOBALS [ 'TYPO3_DB' ]->sql_fetch_assoc ( $res ) )
				{
					if ( $row["evt_woche"] === "0" &&
							$this->last_dayofweek($row["UID"],
												  $row["evt_tag"],
												  $row["taktung"],
												  "+1 week"
												  ) == true )
					{
					
						$weeknumber = (int)date("W")+1;
						
						if ( $this->convertWeek($row, $weeknumber) )
						{
							$t [ ] = $this->createWeek($row, $weeknumber);	
							
						} 
						
					} elseif ( $row [ "evt_woche"] === "1" )
					{
						$monthnumber = (int)date("m");
						
						if (  $this->getFirstDayMonth(
												$row["UID"],
												$row["evt_tag"],
												date("Y"), $monthnumber,
												$row["taktung"]
												) == false )
						{
							++$monthnumber;
							
							if ($this->convertMonth($row, $monthnumber) ) 
							{
								$t [ ] = $this->createMonth($row, $monthnumber);
							} 
						}
					}
					
					if ( $row [ "evt_woche"] === "0" &&
							$this->last_dayofweek( $row["UID"],
						  						   $row["evt_tag"],
												   $row["taktung"] ) == true )
					{
						$weeknumber = (int)date("W");
							
						if ($this->convertWeek($row, $weeknumber))
						{
							$a [ "###TITLE###" ]  = $row [ "PT" ] . " " .$weeknumber; 
							$a [ "###TITLEBILD###" ] = "<img width=\"172\" height=\"235\" src=\"uploads/tx_chraetseltreff/" .$row["filename"].$weeknumber.".jpg\" />";
							$a [ "###URL###" ] = $this->pi_getPageLink ( $GLOBALS [ 'TSFE' ]->id, '',
												 array ( "uid" => $row [ "UID" ],
														"mode" => "s",
														"kw" => $weeknumber,
														"heft" => $row["filename"].$weeknumber.".jpg"
													)
												);			
							$z [ ] = $this->cObj->substituteMarkerArray ( $this->template [ 'ZEITSCHRIFT' ], $a );
						} 
							
					} elseif ($row ["evt_woche"] === "1")
					{
						$monthnumber = (int)date("m");
						
						if ( $this->getFirstDayMonth($row["UID"],
												     $row["evt_tag"],
												     date("Y"), $monthnumber
												) == false
							&& $this->convertMonth($row, $monthnumber)
							)
						{
							//die(print_r($row));
							$a [ "###TITLE###" ]  = $row [ "PT" ] . " " .$monthnumber;
							$a [ "###TITLEBILD###" ] = "<img width=\"172\" height=\"235\" src=\"uploads/tx_chraetseltreff/" .  $row [ "filename" ].sprintf("%02d", $monthnumber).".jpg\" />";
							$a [ "###URL###" ] =   $this->pi_getPageLink ( $GLOBALS [ 'TSFE' ]->id, '',
															array ( "uid" => $row [ "UID" ],
																	"mode" => "s",
																	"kw" => $monthnumber,
																	"heft" =>  $row [ "filename" ].sprintf("%02d", $monthnumber).".jpg"
																   )
															);
							
							$z [ ] = $this->cObj->substituteMarkerArray ( $this->template [ 'ZEITSCHRIFT' ], $a );	
						}
					}
				}
		
				unset ( $s );
				unset ( $m );
				$m ["###TITELBILD###"] = is_array ( $t ) ? implode ( '', $t ) : 'Es tut uns Leid. Es ist ein Fehler aufgetreten.';
				$m ["###BRICK###"] = is_array ( $z ) ? implode ( '', $z ) : '';
					
				$c = $this->cObj->substituteMarkerArray ( $this->template [ 'GALERIE' ], $m );
			}
			break;
		}
		return $this->pi_wrapInBaseClass($c);
	}
}


if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/ch_raetseltreff/pi1/class.tx_chraetseltreff_pi1.php'])
{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/ch_raetseltreff/pi1/class.tx_chraetseltreff_pi1.php']);
}

?>